<template>
  <div class="add-goods-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 添加商品步骤 -->
      <el-steps
        :active="parseInt(activeName)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 整个tab里的tabs都是表单验证的区域，所以要用form包裹整个tab -->
      <el-form
        :model="reqInfo"
        width="50%"
        :rules="goodsFormRules"
        label-position="top"
        ref="addGoodsForm"
      >
        <el-tabs
          tab-position="left"
          v-model="activeName"
          :before-leave="tabsNameChange"
        >
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="reqInfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="reqInfo.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="reqInfo.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="reqInfo.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="selectedKeys"
                :options="categoriesList"
                :props="{
                  expandTrigger: 'hover',
                  ...categoriesListProps
                }"
                :show-all-levels="false"
                clearable
                @change="cascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form-item
              :label="p.attr_name + ':'"
              v-for="p in cateManyList"
              :key="p.attr_id"
            >
              <el-checkbox-group v-model="p.attr_vals">
                <el-checkbox
                  v-for="(val, index) in p.attr_vals"
                  :key="index"
                  :label="val"
                  border
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item
              v-for="p in cateOnlyList"
              :label="p.attr_name"
              :key="p.attr_id"
            >
              <el-input v-model="p.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <!-- action表示图片上传的服务器后台的api地址 -->
            <!--  on-preview表示点击预览图片后触发的事件 -->
            <!-- list-type指定上传列表呈现效果 -->
            <!--  headers指定上传图片的ajax请求的请求头对象 -->
            <!-- on-success图片上传成功后的钩子函数 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="getFile"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor v-model="reqInfo.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="perviewImgDialog" width="50%">
      <img :src="perviewImgSrc" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AddGoodsPage',
  data() {
    return {
      // 选择分类相关属性
      categoriesList: [],
      selectedKeys: [],
      categoriesListProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      reqInfo: {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      goodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_introduce: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' }
        ]
      },
      // 动态参数列表
      cateManyList: [],
      // 静态属性列表
      cateOnlyList: [],
      // tab栏点击后的激活名称，转换成数字绑定给step栏，实现点击tab栏step同步切换
      activeName: '0',
      // 图片上传组件的headers请求头
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      perviewImgDialog: false,
      perviewImgSrc: ''
    }
  },
  methods: {
    // 获取联级选择器的数据
    async getCategories() {
      const { data: res } = await this.$http.get('categories')

      this.categoriesList = res.data
    },
    // 获取商品参数方法
    async getCateParams(sel) {
      const { data: res } = await this.$http.get(
        'categories/' + this.selectedGoodsId + '/attributes',
        { params: { sel } }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取商品参数失败！')
        return false
      }
      if (sel === 'many') {
        // 将每一个分类下的参数以逗号分割为数组
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.$message.success('获取商品参数成功！')
        this.cateManyList = res.data
      } else {
        this.$message.success('获取商品属性成功！')
        this.cateOnlyList = res.data
      }
    },
    cascaderChange() {
      if (this.selectedKeys.length !== 3) return (this.selectedKeys = [])
      // 级联选择器选择后将存放id的数组分割成逗号分隔的字符串保存到reqInfo.goods_cat
      this.reqInfo.goods_cat = this.selectedKeys.join(',')
    },
    // tabs组件的before-leave属性，传入该函数，形参是即将离开的tabs名字和即将进入tabs名字
    tabsNameChange(newName, oldName) {
      // 没选中分类则数组长度不为3，并且即将离开的tabs名字为0时
      if (this.selectedKeys.length !== 3 && oldName === '0') {
        this.$message.error('请选择商品分类！')
        return false
      } else if (newName === '1') {
        // 即将进入的tabs名字为1时，代表进入的时商品参数面版
        // 进入商品参数面板之前，发起请求获取商品参数
        this.getCateParams('many')
      } else if (newName === '2') {
        // 即将进入的tabs名字为2时，代表进入的时商品属性面版
        // 进入商品参数面板之前，发起请求获取商品属性
        this.getCateParams('only')
      }
    },
    // 图片预览点击后触发的钩子函数
    handlePreview(file) {
      this.perviewImgDialog = true
      this.perviewImgSrc = file.response.data.url
    },
    // 移除图片后的钩子函数
    handleRemove(file) {
      // 根据当前钩子函数的形参里的response数据找到数组中地址相同的对象，删除
      this.reqInfo.pics.forEach((item, index) => {
        if (item.pic === file.response.data.tmp_path) {
          this.reqInfo.pics.splice(index, 1)
        }
      })
    },
    // 图片上传成功后的钩子函数
    getFile(file) {
      this.reqInfo.pics.push({ pic: file.data.tmp_path })
    },
    // 添加商品方法
    addGoods() {
      this.$refs.addGoodsForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写必要的表单项！')

        const attrArray = []
        // 处理动态参数将id和属性名，push到数组
        this.cateManyList.forEach((item) => {
          attrArray.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        // 处理静态属性将id和属性名，push到数组
        this.cateOnlyList.forEach((item) => {
          attrArray.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        this.reqInfo.attrs = attrArray

        // 发起请求添加商品
        // 商品的名称必须是唯一的
        const { data: res } = await this.$http.post('goods', this.reqInfo)

        if (res.meta.status !== 201) return this.$message.error('添加商品失败!')

        // 添加成功显示成功页面
        this.$router.push({
          path: '/home/goods/addsuccess',
          params: { title: '添加成功', message: '点击返回' }
        })
      })
    }
  },
  created() {
    this.getCategories()
  },
  computed: {
    selectedGoodsId() {
      return this.selectedKeys[this.selectedKeys.length - 1]
    }
  }
}
</script>

<style lang="less" scope>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.quill-editor {
  margin-bottom: 15px;
  .ql-editor {
    min-height: 350px;
  }
}
</style>
